var express = require("express");
var router = express.Router();

var data = require("../data/news");
const toplist = require("../data/top");
const ads = require("../data/ad");

const types = [
  ...new Set(
    data.map((item) => item.category.cate1_name).filter((item) => item)
  ),
];

router.get("/types", function (req, res, next) {
  res.json({
    success: true,
    types,
  });
});

router.get("/list", function (req, res, next) {
  let { type, page } = req.query;
  page = page || 1;
  let filterData = [...data];
  if (type && type !== "要闻") {
    filterData = filterData.filter((item) => item.category.cate1_name === type);
  }
  const result = filterData.slice((page - 1) * 10, page * 10);

  res.json({
    success: true,
    data: result,
    length: filterData.length,
  });
});

router.get("/top", function (req, res, next) {
  res.json({
    success: true,
    data: toplist,
  });
});

router.get("/ads", function (req, res, next) {
  const { page } = req.query;
  if (page) {
    const i = (page - 1) % 7;

    const result = ads[i];

    res.json({
      success: true,
      data: result,
    });
  } else {
    res.json({
      success: false,
      msg: "参数错误",
    });
  }
});

module.exports = router;
